#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/4/9 15:02
# @Author  : Hbber
# @Version : 0.0.0
# @File    : pyflasher.py
# @Software: PyCharm
# @Org     : AirCas
# @Describe: 使用bash给毫米波芯片烧写程序

# @Last Modify Time          @Version        @Description
# --------------------       --------        -----------
# 2021/4/9 15:02            0.0.1           None

#

import fire
import re
import sys
import os


from flasher.enum_constants import DEVICE, IWR6843_ODS_PORT, IWR6843_ISK_PORT
from flasher.tools import Flasher, get_timestamp_ms


class CMD_Flasher(object):
    """
    适用于双6843+H3集成板的固件下载器
    """

    def __init__(self, device_name: str = 'ISK'):
        self.device_name = 'IWR6843-' + device_name
        if 'ISK' in device_name:
            port = IWR6843_ISK_PORT
        elif 'ODS' in device_name:
            port = IWR6843_ODS_PORT
        elif 'debug' in device_name:
            port = "COM5"
        else:
            raise ValueError(f'device_name 参数只能是: "ODS" or "ISK", 不允许:{device_name}')
        self.port = port
        self.__enter_flash_mode()
        self._flasher = Flasher(uart_port=port, device_type=DEVICE.IWR6843)

    def __enter_flash_mode(self):
        """
        进入下载模式
        :return:
        :rtype:
        """
        print(f'设置{self.device_name}为flashing模式...')
        # do

    def reboot(self):
        """
        复位雷达芯片，进入func mode
        :return:
        :rtype:
        """
        pass

    def get_version(self) -> str:
        """
        获取新版版本信息
        :return:
        :rtype:
        """
        return f'{self.device_name}的version是: {self._flasher.get_version()}'

    def get_status(self) -> str:
        """
        获取芯片状态
        :return:
        :rtype:
        """
        return f'{self.device_name}的status是: {self._flasher.get_status()}'

    def erase_flash(self) -> str:
        """
        擦除flash
        :return:
        :rtype:
        """
        start_time = get_timestamp_ms()
        print(f'开始擦除{self.device_name}的flash...')
        if self._flasher.erase():
            return f'{self.device_name}擦除flash成功, 耗时:{round((get_timestamp_ms() - start_time) / 1000)}秒'
        else:
            return f'{self.device_name}擦除flash失败, 请检查后再试!'

    def download(self, file_path: str = None):
        """
        下载固件到芯片
        :param file_path:
        :type file_path:
        :return:
        :rtype:
        """
        result = re.findall(r'\.[^.\\/:*?"<>|\r\n]+$', file_path)
        if len(result) != 1 or result[0] != '.bin':
            print(f'file_path: {file_path}不是一个合法的Bin文件')
            return
        self._flasher.download(file_path=file_path)

    @staticmethod
    def help():
        print('''
*******************************************************************************************
*                            PY-Flasher: UniFlash in Python                               *
*                    (c) 2021 HBBER <zhanghao190@mails.ucas.ac.cn>                        *
*                        https://gitee.com/haobaobao/py-flasher                           *
*******************************************************************************************

python3 pyflasher.py [命令]

可选命令：
      get_status [device_name]            - 获取芯片状态
                                            device_name 表示芯片名称, 合法值: "ISK", "ODS" 
      get_version [device_name]           - 获取芯片硅版本
                                            device_name 表示芯片名称, 合法值: "ISK", "ODS"
      download [device_name] [file_path]  - 下载bin文件到芯片。
                                            device_name 表示芯片名称, 合法值: "ISK", "ODS"
                                            file_path 表示bin文件地址（可选: 默认值为 Demo文件）
      erase [device_name]                 - 擦除外挂FLASH
                                            device_name 表示芯片名称, 合法值: "ISK", "OD

NOTE: 如需更多帮助，请访问：https://gitee.com/haobaobao/py-flasher/blob/master/README.md

            ''')


if __name__ == '__main__':
    flasher = None
    if len(sys.argv) == 1:
        CMD_Flasher.help()
    elif ('-h' in sys.argv) or ('--help' in sys.argv):
        CMD_Flasher.help()
    else:
        try:
            fire.Fire(CMD_Flasher)
        except Exception as e:
            print(f'创建下载器失败, 原因{e}')
            exit(-1)
